$(function () {
    /**  左侧折叠菜单 */
    var trigger = $('.hamburger'),
        overlay = $('.overlay'),
        isClosed = false;

    trigger.click(function () {
        hamburger_cross();
    });

    function hamburger_cross() {

        if (isClosed == true) {
            overlay.hide();
            trigger.removeClass('is-open');
            trigger.addClass('is-closed');
            isClosed = false;
        } else {
            overlay.show();
            trigger.removeClass('is-closed');
            trigger.addClass('is-open');
            isClosed = true;
        }
    }

    $('[data-toggle="offcanvas"]').click(function () {
        $('#wrapper').toggleClass('toggled');
    });


    // 自定义航线生成时筛选用filter
    ol.customs = {};
    // restful服务器ip及port
    ol.customs.server = "http://113.200.57.224:22280/";
    // 动态请求服务器端航线信息
    ol.customs.url = null;
    // 用于为国际、国内及全球航线的筛选而设计。
    ol.customs.viewFilter = undefined;
    // 用于控制绘制航线粗细
    ol.customs.flightWidth = 0.5;

    /** 天地路网地图 */
    var tile1 = new ol.layer.Tile({
        title: "天地图路网",
        source: new ol.source.XYZ({
            url: "http://t4.tianditu.com/DataServer?T=vec_w&x={x}&y={y}&l={z}"
        })
    });
    /** 天地图卫星影像 */
    var tile2 = new ol.layer.Tile({
        title: "天地图卫星影像",
        source: new ol.source.XYZ({
            url: 'http://t3.tianditu.com/DataServer?T=img_w&x={x}&y={y}&l={z}'
        })
    });
    /** 天地图文字标注 */
    var tile3 = new ol.layer.Tile({
        title: "天地图文字标注",
        source: new ol.source.XYZ({
            url: 'http://t3.tianditu.com/DataServer?T=cva_w&x={x}&y={y}&l={z}'
        })
    });

    /** openlayer对象 */
    var map = new ol.Map({
        target: 'map',
        layers: [ tile1, tile3 ],
        view: new ol.View({
            center: ol.proj.fromLonLat([0,50]), // 设置地图中心点，默认北半球
            zoom: 2
        })
    });

    /** 空港数据源 */
    var airportSource = new ol.source.Vector({
        wrapX: false
    });

    /** 航线数据源 */
    var flightsSource = new ol.source.Vector({
        wrapX: false,
        attributions: '航班信息可视化查询',
        loader: function() {
            // 加载json航线数据
            // 格式
            if(ol.customs.url == null) return;
            // XHR替换fetch进行异步处理
            fetch(ol.customs.url).then(function(response) {
                return response.json(); // 返回结果转换为json对象
            }).then(function(json) {
                var flightsData = json.fleet.records;
                // 遍历航线集合获取from和to
                for (var i = 0; i < flightsData.length; i++) {
                    var flight = flightsData[i];
                    // 获取航线中的城市4位缩写编码
                    var flightno = flight[0];   // 航线名称
                    var airline = flight[1];    // 航空公司
                    var airplane = flight[2];   // 机型
                    var from_code = flight[3];  // 出发城市
                    var to_code = flight[4];    // 到达城市

                    // 动态检索airportGPS.js中的空港缩写，获取空港信息(坐标、名称)
                    var apt_from = geoCoordMap[from_code];
                    var apt_to = geoCoordMap[to_code];

                    // 过滤航线中没有查询到的空港
                    if(apt_from == undefined || apt_to == undefined) continue;
                    // 避免起点和终点一致的航线
                    if(from_code == to_code) continue;
                    // 空港名称
                    var from_name = apt_from[2];
                    var to_name = apt_to[2];
                    // 标记航线类型(国内、国际)
                    var ftype = (apt_from[1] == 'China' && apt_from[1] == apt_to[1]) ? 'local' : 'global';

                    // 通过filter过滤绘制的航线
                    if(ol.customs.viewFilter && ol.customs.viewFilter != ftype) continue;

                    // 查询航线上已有航班
                    var having_feature = flightsSource.getFeatureById(from_code + '_' + to_code);
                    if(having_feature != null){
                        // 为已有航线添加航班信息
                        var flights = having_feature.get("flights");
                        flights.push({no: flightno, airline: airline, airplane: airplane});
                        console.log("bingo!");
                    }else {
                        // 使用arc创建一个墨卡托大圆航线的坐标
                        var arcGenerator = new arc.GreatCircle(
                            {x: apt_from[6], y: apt_from[5]},
                            {x: apt_to[6], y: apt_to[5]});

                        // 生成航线
                        var arcLine = arcGenerator.Arc(150, {offset: 10});
                        if (arcLine.geometries.length === 1) {
                            // 把arc生成坐标点转换为ol可以识别坐标系
                            var line = new ol.geom.LineString(arcLine.geometries[0].coords);
                            // WGS84坐标转换为Mercator坐标
                            line.transform(ol.proj.get('EPSG:4326'), ol.proj.get('EPSG:3857'));
                            // feature中包含所有需要绘制的航班坐标点
                            var feature = new ol.Feature({
                                id: from_code + '_' + to_code,  // 出发城市_到达城市(拼接后的字符串作为唯一标识)
                                geometry: line,
                                from: from_name,
                                to: to_name,
                                type: ftype,
                                flights: [{no: flightno, airline: airline, airplane: airplane}]
                            });
                            // 添加绘制航线需要的feature
                            flightsSource.addFeature(feature);
                        }
                        // 航线标注完了，接下来标注航线的起飞和到达空港坐标
                        addAirportFeature(from_code, apt_from);
                        addAirportFeature(to_code, apt_to);
                    }
                }

                // 查询单一航线时定制地图的中心点坐标和航线绘制粗细
                if(flightsData.length == 1){
                    var coords = flightsSource.getFeatures()[0].getGeometry().getCoordinates();
                    var cd = coords[coords.length / 2];
                    map.setView(new ol.View({
                        center: cd,
                        zoom: 4
                    }));
                    ol.customs.flightWidth = 4;
                }
            });
        }
    });

    /** 自定义方法：添加航线Feature */
    function addAirportFeature(apt_code, airportInfo){
        var apt_name = airportInfo[2];

        var apt_geom = new ol.geom.Point(
            ol.proj.transform(
                [parseFloat(airportInfo[6]), parseFloat(airportInfo[5])],
                'EPSG:4326', 'EPSG:3857'));
        var feature = new ol.Feature({
            id: apt_code,
            geometry: apt_geom,
            aptname: apt_name
        });
        airportSource.addFeature(feature);
    }

    /** flightsLayer */
    var flightsLayer = new ol.layer.Vector({
        source: flightsSource,
        style: function(feature){
            // 根据航线特征，动态定制航线的线条样式
            var flightStyle = new ol.style.Style();
            var flightStroke = new ol.style.Stroke();
            flightStyle.setStroke(flightStroke);

            if(feature.get("type") == 'local'){
                // 国内航线样式
                flightStroke.setColor('#03A9F4');
                flightStroke.setWidth(ol.customs.flightWidth);
            }else{
                // 国际航线样式
                flightStroke.setColor('#FFC107');
                flightStroke.setWidth(ol.customs.flightWidth);
            }
            return flightStyle;
        }
    });

    /** airPortsLayer */
    var airPortsLayer = new ol.layer.Vector({
        source: airportSource
    });

    /** 创建弹出窗口用来显示航线信息  */
    var container = document.getElementById('popup'); // 弹出窗口
    var content = document.getElementById('popup-content'); // 弹出窗口内容
    var closer = document.getElementById('popup-closer'); // 弹出窗口关闭按钮
    var viewport = map.getViewport();
    $(viewport).append(container);

    /** 添加一个点击控制器来隐藏弹出窗口 */
    closer.onclick = function() {
        container.style.display="none";
        closer.blur();
        return false;
    };

    /** 光标移动交互 */
    var selectPointerMove = new ol.interaction.Select({
        condition: ol.events.condition.pointerMove
    });
    map.addInteraction(selectPointerMove);

    /** 光标移动事件(航线及城市) */
    selectPointerMove.on('select', function(e) {
        // geometry类型:LineString(航线)或Point(城市)

        // 清理所有空港Feature的style
        airportSource.forEachFeature(function(feature){
            feature.setStyle(null);
        });

        if(e.selected.length > 0) {
            // 为选择的空港通过style实现动态名称提示
            if(e.selected[0].getGeometry().getType() == "Point") {
                var airPortFeature = e.selected[0];
                airPortFeature.setStyle(
                    new ol.style.Style({
                        text: new ol.style.Text({
                            text: airPortFeature.get('aptname'),
                            fill: new ol.style.Fill({
                                color: '#000'
                            }),
                            stroke: new ol.style.Stroke({
                                color: '#fff',
                                width: 3
                            })
                        })
                    })
                );
            }
            // 为选择的航线动态添加航班提示弹出窗口
            if(e.selected[0].getGeometry().getType() == "LineString"){
                container.style.display = "block";
                var flightFeature = e.selected[0];

                content.innerHTML =
                    '<p style="color:#6699CC">' + flightFeature.get("from") + " 至 " + flightFeature.get("to") + '</p>';
                var flights = flightFeature.get("flights");
                for(var index in flights) {
                    // 查询航班晚点率（到港大于3个小时以上或者取消的航班统一算做晚点）
                    var url = ol.customs.server + "/flightdata/api.php/flight?columns=fleet_id,cancelled,delay&filter[]=delay,nis,null&filter[]=fleet_id,eq," + flights[index].no;
                    var count = 0;
                    var rate = 0;
                    fetch(url).then(function(response) {
                        return response.json();
                    }).then(function(json) {
                        var records = json.flight.records;
                        for(var i = 0; i < records.length; i++){
                            if (records[i][1] == 1) count++;
                            if (records[i][2] > 10800) count++;
                        }
                        rate = parseInt((count / records.length) * 100);

                        content.innerHTML +=
                            '<span style="color:#333333">航班号: </span><span style="color:#42A5F5">' + flights[index].no + '</span>' +
                            '<span style="color:#000;margin-left:5px;">航空公司: </span><span style="color:#FFA726">' + flights[index].airline + '</span>' +
                            '<span style="color:#000;margin-left:5px;">晚点率: </span><span style="color:#F06292">' + rate + '%</span><br/>';
                    });
                }
            }
        }
    });

    /** Action:load_global(加载常规地图) */
    $(".load_map_normal").click(function(){
        // 折叠侧边栏
        hamburger_cross();
        // 隐藏查询窗口
        $('#cityFilterBox').hide();
        $('#wrapper').toggleClass('toggled');
        // css transform结束后刷新地图
        var runOnce = 0;
        $("#sidebar-wrapper").on('transitionend webkitTransitionEnd',function(){
            runOnce++;
            if(runOnce > 1) return;
            container.style.display="none";
            map.addLayer(tile1);
            map.addLayer(tile3);
        });
    });

    /** Action:load_global(加载卫星地图) */
    $(".load_map_image").click(function(){
        // 折叠侧边栏
        hamburger_cross();
        // 隐藏查询窗口
        $('#cityFilterBox').hide();
        $('#wrapper').toggleClass('toggled');
        // css transform结束后刷新地图
        var runOnce = 0;
        $("#sidebar-wrapper").on('transitionend webkitTransitionEnd',function(){
            runOnce++;
            if(runOnce > 1) return;
            container.style.display="none";
            map.addLayer(tile2);
            map.addLayer(tile3);
        });
    });

    /** Action:filter_airport(按区域查询) */
    $(".filter_airport").click(function(){
        // 弹出查询窗口
        $('#cityFilterBox').show();
    });

    /** Action:load_full(加载全部航线) */
    $(".load_full").click(function(){
        // 折叠侧边栏
        hamburger_cross();
        // 隐藏查询窗口
        $('#cityFilterBox').hide();
        $('#wrapper').toggleClass('toggled');
        // css transform结束后刷新地图
        var runOnce = 0;
        $("#sidebar-wrapper").on('transitionend',function(){
            runOnce++;
            if(runOnce > 1) return;
            ol.customs.viewFilter = undefined;
            flightsSource.clear();
            airportSource.clear();
            container.style.display="none";

            map.setView(new ol.View({
                center: ol.proj.fromLonLat([0,50]),
                zoom: 2
            }));

            // 指定加载的url资源
            ol.customs.url = ol.customs.server + 'flightdata/api.php/fleet?exclude=airport_s3,airport_d3';
            map.removeLayer(flightsLayer);
            map.removeLayer(airPortsLayer);
            map.addLayer(flightsLayer);
            map.addLayer(airPortsLayer);
        });
    });

    /** Action:load_local(加载国内航线)  */
    $(".load_local").click(function(){
        // 折叠侧边栏
        hamburger_cross();
        // 隐藏查询窗口
        $('#cityFilterBox').hide();
        $('#wrapper').toggleClass('toggled');
        // css transform结束后刷新地图
        var runOnce = 0;
        $("#sidebar-wrapper").on('transitionend webkitTransitionEnd',function(){
            runOnce++;
            if(runOnce > 1) return;
            ol.customs.viewFilter = "local";
            flightsSource.clear();
            airportSource.clear();
            container.style.display="none";

            map.setView(new ol.View({
                center: ol.proj.fromLonLat([108.75605,34.441154]),
                zoom: 4
            }));

            // 指定加载的url资源
            // 指定加载的url资源
            ol.customs.url = ol.customs.server + 'flightdata/api.php/fleet?exclude=airport_s3,airport_d3';
            map.removeLayer(flightsLayer);
            map.removeLayer(airPortsLayer);
            map.addLayer(flightsLayer);
            map.addLayer(airPortsLayer);
        });
    });

    /** Action:load_global(加载国际航线) */
    $(".load_global").click(function(){
        // 折叠侧边栏
        hamburger_cross();
        // 隐藏查询窗口
        $('#cityFilterBox').hide();
        $('#wrapper').toggleClass('toggled');
        // css transform结束后刷新地图
        var runOnce = 0;
        $("#sidebar-wrapper").on('transitionend webkitTransitionEnd',function(){
            runOnce++;
            if(runOnce > 1) return;
            ol.customs.viewFilter = "global";
            flightsSource.clear();
            airportSource.clear();
            container.style.display="none";

            map.setView(new ol.View({
                center: ol.proj.fromLonLat([0,50]),
                zoom: 2
            }));

            // 指定加载的url资源
            // 指定加载的url资源
            ol.customs.url = ol.customs.server + 'flightdata/api.php/fleet?exclude=airport_s3,airport_d3';
            map.removeLayer(flightsLayer);
            map.removeLayer(airPortsLayer);
            map.addLayer(flightsLayer);
            map.addLayer(airPortsLayer);
        });
    });

    /** Action:btn_filter_flight(查询航班信息) */
    $("#btn_filter_flight").click(function () {
        var flightno = $("#flightno").val();
        if($.trim(flightno) == "") return;

        // 折叠侧边栏
        hamburger_cross();
        // 隐藏查询窗口
        $('#cityFilterBox').hide();
        $('#wrapper').toggleClass('toggled');

        var runOnce = 0;
        $("#sidebar-wrapper").on('transitionend webkitTransitionEnd',function(){
            runOnce++;
            if(runOnce > 1) return;
            flightsSource.clear();
            airportSource.clear();
            container.style.display="none";

            // 指定加载的url资源
            ol.customs.url = ol.customs.server + "flightdata/api.php/fleet?exclude=airport_s3,airport_d3&filter=id,eq," + $.trim(flightno);
            map.removeLayer(flightsLayer);
            map.removeLayer(airPortsLayer);
            map.addLayer(flightsLayer);
            map.addLayer(airPortsLayer);
        });
    });

    /** Action:from_airport_focus */
    var input;
    $("#from_airport, #to_airport").focus(function () {
        input = $(this);
       $(".cityFilterIn").show();

       $('#cityFilterBox span').click(function() {
           input.val($(this).text());
           input.attr("code", $(this).attr('code'));
           $(".cityFilterIn").hide();
       })
    });

    /** Action:btn-search-demo(查询空港信息) */
    $("#btn-search-demo").click(function(){
        // 折叠侧边栏
        hamburger_cross();
        // 隐藏查询窗口
        $("#cityFilterBox").hide();
        $('#wrapper').toggleClass('toggled');
        // css transform结束后刷新地图
        var runOnce = 0;
        $("#sidebar-wrapper").on('transitionend webkitTransitionEnd',function(){
            runOnce++;
            if(runOnce > 1) return;
            ol.customs.viewFilter = undefined;
            flightsSource.clear();
            airportSource.clear();
            container.style.display="none";

            // 获取选择的出发和到达空港
            var from = $('#from_airport').attr('code');
            var to = $('#to_airport').attr('code');
            ol.customs.url = ol.customs.server + "flightdata/api.php/fleet?";

            // 过滤空查询条件
            if(from == undefined && to == undefined){
                return;
            }
            // 组合查询条件url
            var roles = [];
            if(from != undefined ) {
                roles.push("filter[]=airport_s3,eq," + from);
            }
            if(to != undefined){
                roles.push("filter[]=airport_d3,eq," + to);
            }
            // 指定加载的url资源
            ol.customs.url += roles.join("&") + "&exclude=airport_s3,airport_d3";

            map.removeLayer(flightsLayer);
            map.removeLayer(airPortsLayer);
            map.addLayer(flightsLayer);
            map.addLayer(airPortsLayer);
        });
    });
});

/** 航线查询的筛选 */
$('#cityFilterBox').on('click', '.cityFilterHead li', function () {
    $(this).addClass('cur').siblings('.cur').removeClass();

    var index = $(this).index();
    var thisTableId = $(this).parents('.cityFilterHead').siblings('.cityFilterTable').attr('id');
    if (thisTableId == 'cityFilterTable') {
        $('#cityFilterTable>div').eq(index).show();
        $('#cityFilterTable>div').eq(index).siblings().hide();
    } else {
        $('#cityFilterTable2>div').eq(index).show();
        $('#cityFilterTable2>div').eq(index).siblings().hide();
    }
});

$('#cityFilterBox').on('click', '#hotOutTog,#hotInTog', function () {
    if ($(this).attr('id') == 'hotInTog') {
        $('.cityFilterIn').show().siblings().hide();
        $('.cityFilterIn').children('.cityFilterHead').find('li:first').addClass('cur').siblings().removeClass('cur');
        $('.cityFilterIn .cityFilterTable').children('div:first').show().siblings().hide();
    } else {
        $('.cityFilterOut').show().siblings().hide();
        $('.cityFilterOut').children('.cityFilterHead').find('li:first').addClass('cur').siblings().removeClass('cur');
        $('.cityFilterOut .cityFilterTable').children('div:first').show().siblings().hide();
    }
    $('.cityFilterInput').show();
});

